#include "doge-cmd-parser.h"



static int _is_blank(char c)
{
	if (c == ' ')
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int _str_cmp(char *str1, char *str2)
{
	while (*str1 != '\0' && *str1 == *str2)
	{
		str1++;
		str2++;
	}

	int t = *str1 - *str2;
	if (t == 0)
		return 0;
	else if (t > 0)
		return 1;
	else
		return -1;
}

#if 1

void doge_cmd_parser(char *buf,  dcmd_list_t *lists, int list_len)
{
	char arg[CMD_ARG_MAX_NUM][CMD_ONE_ARG_MAX_LEN] = {0};
    char *cmd[CMD_ARG_MAX_NUM];
	char argc = 0;
	char index = 0;
	char  n = 0;
	char i = 0;
	int pos;

	for (i = 0; i < CMD_ARG_MAX_NUM; i++)
    {
        cmd[i] = arg[i];
    }

	char *pStr = (char *)buf;

	while (_is_blank(*pStr))    // 去掉命令前的空格
	{
		pStr++;
	}

	argc++;

	while (*pStr != '\0')
	{
		if (_is_blank(*pStr))
		{
			pStr++;
			index++;
			n = 0;
			argc++;
		}
        if (index >= CMD_ARG_MAX_NUM)
            break;

		arg[index][n++] = *pStr;
		pStr++;
	}
//	printf("index = %d, arg[0] = %s arg[1] = %s, arg[2] = %s\r\n",  index, arg[0], arg[1], arg[2]);
	if (!lists) return;

//	printf("argc = %d list_len = %d\r\n", argc, list_len);
	for (pos = 0; pos < list_len; pos++)
	{
		if (_str_cmp(arg[0], lists[pos].cmd) == 0)
		{
			if (!lists[pos].cb) return;

			lists[pos].cb(argc, cmd);
		}
	}
}
#else
void doge_cmd_parser(char *buf,  dcmd_list_t *lists, int list_len)
{
	char **arg;
	char argc = 0;
	char index = 0;
	char  n = 0;
	char i = 0;
	int pos;

	arg = (char **)malloc(CMD_ARG_MAX_NUM*CMD_ONE_ARG_MAX_LEN);
	if (!arg)
        return;

    printf("allocate success\r\n");
	char *pStr = (char *)buf;

	while (is_blank(*pStr))    // 去掉命令前的空格
	{
		pStr++;
	}

	while (*pStr != '\0')
	{
		if (is_blank(*pStr))
		{
			pStr++;
			index++;
			n = 0;
			argc++;
		}

		arg[index][n++] = *pStr;
		pStr++;
	}
	printf("index = %d, arg[0] = %s arg[1] = %s, arg[2] = %s\r\n",  index, arg[0], arg[1], arg[2]);
	if (!lists) return;

	printf("argc = %d list_len = %d\r\n", argc, list_len);
	for (pos = 0; pos < list_len; pos++)
	{
		if (_str_cmp(arg[0], lists[pos].cmd) == 0)
		{
			if (!lists[pos].cb) return;

			lists[pos].cb(argc, arg);
		}
	}
}


#endif
